package com.simple.common.framework.retrofit;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.simple.common.framework.context.Contexts;
import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

/**
 * @author yasud
 * @date 2021年03月03日 09:30
 * @description
 */
public class Retrofits {

    Cache<String, Retrofit> cache = CacheBuilder.newBuilder()
            .maximumSize(23)
            .weakKeys()
            .weakValues()
            .build();

    public static Retrofits SINGLE;

    @Autowired
    public void setIt() {
        SINGLE = this;
    }

    /**
     * 创建对象
     *
     * @return
     */
    @SneakyThrows
    public Retrofit createRetrofit(String basePath) {
        if (StringUtils.isNotBlank(basePath) && !basePath.endsWith("/")) {
            basePath += "/";
        }
        OkHttpClient okHttpClient = Contexts.BEANFACTORY.getBean(OkHttpClient.class);
        String s = basePath;
        return cache.get(basePath, () -> {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            Retrofit build = new Retrofit.Builder()
                    .validateEagerly(true)
                    .addConverterFactory(JacksonConverterFactory.create(mapper))
                    .client(okHttpClient)
                    .baseUrl(s)
                    .build();
            return build;
        });
    }
}
